import {defineStore} from "pinia";
import { asyncRouterMap } from "../../router/asyncRouterMap.ts";
import router from "../../router";
import {RouteRecordRaw} from "vue-router";

// console.log(router);

interface permissionType{
    permissionCodeList: string[],
    asyncRouters: any[],
}

const usePermissionStore = defineStore('permission', {
    state: (): permissionType => {
        return {
            permissionCodeList: [],
            asyncRouters: []
        }
    },
    actions: {
        setPermissionCodeList(codeList: string[]): void {
            this.permissionCodeList = codeList
        },
        getAsyncRoutes(_routers: RouteRecordRaw[]) {
            // this.asyncRouters = routers
            // console.log(this.asyncRouters)
            return this.asyncRouters = filterAsyncRouter(asyncRouterMap, this.permissionCodeList)
        },
        async addRoutes() {
            return this.asyncRouters = filterAsyncRouter(asyncRouterMap, this.permissionCodeList)
        }
    },
    getters: {

    }
})

export default usePermissionStore

function filterAsyncRouter(routerMap: RouteRecordRaw[], roles: any) {
    const accessedRouters = routerMap.filter((route: any) => {
        if (hasPermission(route, roles)) {
            if (route.children && route.children.length) {
                route.children = filterAsyncRouter(route.children, roles)
            }
            return true
        }
        return false
    })
    return accessedRouters
}


function hasPermission(route: any, permission: any): boolean {
    if (route.meta && route.meta.code) {
        let flag: boolean = false
        for (let i: number = 0; i < permission.length; i++) {
            flag = permission[i] === route.meta.code
            if (flag) {
                return true
            }
        }
        return false
    }
    return true
}
